package com.ymm.handler.security;

import com.alibaba.fastjson.JSON;
import com.ymm.domain.vo.ResponseResult;
import com.ymm.enums.AppHttpCodeEnum;
import com.ymm.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        e.printStackTrace();
        ResponseResult result = null;

        // 判断异常的类型，根据异常的类型提示不同的信息
        if (e instanceof InsufficientAuthenticationException) {
            // 需要验证的链接没有携带token
            result = ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_TOKEN);
        } else if (e instanceof BadCredentialsException) {
            // 用户名或者密码错误
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
            // TODO:需要验证的链接携带的token非法解析不出来
        } else if (e instanceof InternalAuthenticationServiceException) {
            result = ResponseResult.errorResult(AppHttpCodeEnum.USER_HAS_NOT_EXISTED);
        } else {
            result = ResponseResult.errorResult(AppHttpCodeEnum.UNKNOWN_ERROR);
        }

        // 响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
